<?php
declare (strict_types = 1);

namespace app\controller;

use think\Request;
use think\facade\Config;


class Wechat
{
    public function __construct() {
        $this->access_token = $this->getAccessToken();
    }

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }

    /**
     * 获取微信小店商品列表
     * @return \think\Response
     */
    public function getShopProducts()
    {
        // 读取配置
        $accessToken = $this->getAccessToken();
        if (!$accessToken) {
            return json(['error' => '获取access_token失败'], 500);
        }
        // 微信小店商品列表API
        $url = "https://api.weixin.qq.com/merchant/getbystatus?access_token={$accessToken}";
        $data = [
            'status' => 0 // 0:全部, 1:上架, 2:下架
        ];
        $response = $this->httpPost($url, $data);
        var_dump($response);exit;
        return json($response);
    }

    /**
     * 根据 order_id 获取订单信息
     */
    public function getInfoByOrderId($list) {
        $list_info = [];
        if (!$this->access_token) {
            return json(['error' => '获取access_token失败'], 500);
        }
        $url = "https://api.weixin.qq.com/channels/ec/order/get?access_token={$this->access_token}";
        // $list = ['3728077525697829888'];
        foreach ($list as $value) {
                    $data = [
                        'order_id' => $value
                    ];
                    
            $response = $this->httpPost($url, $data);
            $aftersale_order_list = $response['order']['aftersale_detail']['aftersale_order_list'];
            if (count($aftersale_order_list) > 0) {
                $aftersale_order_id = $aftersale_order_list[0]['aftersale_order_id'];
                $aftersale_result = $this->getInfoByAfterSaleOrderId($aftersale_order_id);
                $data = $aftersale_result->getData();
                $aftersale_status = $data['after_sale_order']['status'];
                $amount = $data['after_sale_order']['refund_info']['amount'];
                // var_dump($aftersale_result);exit;
                
            } else {
                $aftersale_status = 0;
            }

            $delivery_product_info = $response['order']['order_detail']['delivery_info']['delivery_product_info'];
            $pay_info = $response['order']['order_detail']['pay_info'];
            $list_info[] = [
                'name' => $response['order']['order_detail']['product_infos'][0]['title'],
                'delivery_time' => count($delivery_product_info) > 0 ?$delivery_product_info[0]['delivery_time'] : 0,
                'sku_des' => $response['order']['order_detail']['product_infos'][0]['sku_attrs'][0]['attr_key'],
                'pay_time' => isset($pay_info['pay_time'])?$pay_info['pay_time']:0,
                'real_price' => $response['order']['order_detail']['product_infos'][0]['real_price'],
                'sku_cnt' => $response['order']['order_detail']['product_infos'][0]['sku_cnt'],
                'status' =>$response['order']['status'], 
                'aftersale_status' => $aftersale_status,
                'amount' => isset($amount)? $amount : 0,
            ];
    
        }
        var_dump($list_info);exit;
        return json($list_info);

    }


    /**
     * 获取微信小店access_token
     * @param array $config
     * @return string|null
     */
    private function getAccessToken()
    {
        $app_id = Config::get('wechatshop.app_id');
        $app_secret = Config::get('wechatshop.app_secret');
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$app_id}&secret={$app_secret}";
        $result = $this->httpGet($url);
        if (isset($result['access_token'])) {
            return $result['access_token'];
        }
        return null;
    }

    /**
     * 发送GET请求
     */
    private function httpGet($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output, true);
    }

    /**
     * 发送POST请求
     */
    private function httpPost($url, $data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_UNICODE));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output, true);
    }

    public function orderList($start_time, $end_time) {
        echo 4321421;exit;
        // $accessToken = $this->getAccessToken();
        if (!$this->access_token) {
            return json(['error' => '获取access_token失败'], 500);
        }
        $list = [];
        $url = "https://api.weixin.qq.com/channels/ec/order/list/get?access_token={$this->access_token}";

        $time = ($end_time - $start_time)/5;
        for ($start_time; $start_time < $start_time + $time; $start_time += $time) {
            $data = [
                'create_time_range' => [
                    'start_time' => $start_time,
                    'end_time' => $start_time + $time,
                ],
                'page_size' => 50,
            ];
            
            do {
                $response = $this->httpPost($url, $data);
                if ($response['next_key']) {
                    $data['next_key'] = $response['next_key'];
                }
                $list = array_merge($list, $response['order_id_list']);
            } while ($response['has_more']);
            
        }
        // var_dump($list);exit;
        $this->getInfoByOrderId($list);
        //return json($response);

    }

    /**
     * 获取微信小店订单列表与售后明细
     * @return \think\Response
     */
    public function getShopOrders()
    {
        $accessToken = $this->getAccessToken();
        if (!$accessToken) {
            return json(['error' => '获取access_token失败'], 500);
        }
        // 微信小店订单列表API
        $url = "https://api.weixin.qq.com/merchant/order/getbyfilter?access_token={$accessToken}";
        $data = [
            'status' => 0, // 0:全部, 1:待发货, 2:已发货, 3:已完成, 4:已关闭
            'begin_time' => 0, // 开始时间戳，0表示不限制
            'end_time' => 0, // 结束时间戳，0表示不限制
            'page' => 1, // 页码
            'page_size' => 10 // 每页数量
        ];
        $response = $this->httpPost($url, $data);
        return json($response);
    }

    /**
     * 根据售后单号获取售后单信息
     * @param number $id
     */
    public function getInfoByAfterSaleOrderId($id) {
        if (!$this->access_token) {
            return json(['error' => '获取access_token失败'], 500);
        }
        $url = "https://api.weixin.qq.com/channels/ec/aftersale/getaftersaleorder?access_token={$this->access_token}";
        $data = ['after_sale_order_id' => $id];
        $response = $this->httpPost($url, $data);
        return json($response);
    }
}
